﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Linq.Expressions;
using Newtonsoft.Json.Linq;

using CanDoo;
using CanDoo.Core;
using CanDoo.Data;
using CanDoo.Web;
using CanDoo.FineUI;
using CanDoo.Extensions;
using CanDoo.NPOI;
using CanDoo.Oil.Core.Models;
using CanDoo.Oil.Core.Contracts;
using CanDoo.Admin.Core.Contracts;
using FineUIPro;

namespace CanDoo.Oil.WebApp.storeOilSalesSerialNum
{
    public partial class Import : PageBase
    {
        public IOilSalesSerialNumContract OilSalesSerialNumContract { get; set; }

        public List<string> srcHeader1 = new List<string>();

        protected void Page_Load(object sender, EventArgs e)
        {
            srcHeader1.Add("序列号"); //0
            srcHeader1.Add("密钥"); //1
            srcHeader1.Add("终端号"); //2
            srcHeader1.Add("生产日期"); //3
            srcHeader1.Add("生产批次"); //4

            for (int j = 0; j < srcHeader1.Count; j++)
            {
                FineUIPro.BoundField column = Grid1.FindColumn("L" + j + "") as FineUIPro.BoundField;
                column.HeaderText = srcHeader1[j];
                column.DataField = srcHeader1[j];
                column.Hidden = false;
            }

            if (!IsPostBack)
            {
                if (Web.Request.QueryString("IS_RETRUN") != "")
                    btnClose.Hidden = false;
                btnSave.Enabled = false;
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (!ed_File.HasFile)
            {
                Alert.ShowInTop("请先选择要上传的文件！");
            }
            string Path = System.Web.HttpContext.Current.Request.MapPath("~/UploadFiles/SerialNum/");

            string FileName = ed_File.FileName.Right(ed_File.FileName.Length - ed_File.FileName.LastIndexOf('\\') - 1);
            string NewFileName = RandomExtensions.RandFileName() + "_" + FileName;
            ed_File.SaveAs(Path + NewFileName);
            ed_filePath.SetValue(Path + NewFileName);

            System.Data.DataTable dt = NPOIHelper.Import(Path + NewFileName);
            if (dt.Rows.Count == 0)
            {
                Alert.ShowInTop("导入excel文件中没有任何数据");
                return;
            }
            var total = dt.Rows.Count;

            var header1 = NPOIHelper.GetRow(Path + NewFileName, 0);

            var msg = CheckTemplate(header1, srcHeader1);
            if (!msg.IsNull())
            {
                FineUIPro.Alert.ShowInTop(msg);
                return;
            }

            bool HaveError = false;
            for (int i = 0; i < total; i++)
            {
                for (int k = 0; k < srcHeader1.Count; k++)
                {
                    if (dt.Rows[i][srcHeader1[k]].ToString().Trim() == "")
                    {
                        if (srcHeader1[k] != "备注")
                        {
                            dt.Rows[i][srcHeader1[k]] = "<span style='color:red;font-weight:bold;'>不允许为空</span>";
                            HaveError = true;
                        }
                    }
                    else
                    {

                    }
                }
            }
            Grid1.DataSource = dt;
            Grid1.DataBind();
            if (!HaveError)
            {
                Alert.ShowInTop("数据通过校验，确认后，请点击导入按钮，完成导入！");
                btnSave.Enabled = true;
            }
            else
            {
                Alert.ShowInTop("部分数据匹配失败！，请注意红色部分！");
                btnSave.Enabled = false;
            }
        }

        private string CheckTemplate(List<string> header1, List<string> srcHeader1)
        {
            string msg = "";
            if (header1.Count != srcHeader1.Count)
            {
                ////done::模板不符合要求提示
                msg = "模板不对，建议使用给定的模板";
                return msg;
            }
            for (int i = 0; i < header1.Count; i++)
            {
                if (header1[i] != srcHeader1[i])
                {
                    ////done::模板不符合要求提示
                    msg += string.Format("模板不对，原因：字段不符合要求，现为 {0} ,应为 {1}</br>", header1[i], srcHeader1[i]);
                }
            }
            return msg;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            System.Data.DataTable dt = NPOIHelper.Import(ed_filePath.GetValue().ToString());
            if (dt.Rows.Count == 0)
            {
                Alert.ShowInTop("导入excel文件中没有任何数据");
                return;
            }

            var total = dt.Rows.Count;

            var header1 = NPOIHelper.GetRow(ed_filePath.GetValue().ToString(), 0);

            var msg = CheckTemplate(header1, srcHeader1);
            if (!msg.IsNull())
            {
                FineUIPro.Alert.ShowInTop(msg);
                return;
            }

            var OilSalesSerialNumList = new List<OilSalesSerialNum>();
            for (int i = 0; i < total; i++)
            {
                var mEntity = new OilSalesSerialNum();
                mEntity.Id = IdMaker.NewId();
                mEntity.WarehouseId = Web.Request.QueryString("WareHouseId").ToLong();
                mEntity.InStoreTypeId = Web.Request.QueryString("InType").ToLong();
                mEntity.InStoreId = Web.Request.QueryString("EntityId").ToLong();
                mEntity.ProductId = Web.Request.QueryString("ProductId").ToLong();
                mEntity.SerialNumber = dt.Rows[i]["序列号"].ToString().Trim();
                mEntity.Secret = dt.Rows[i]["密钥"].ToString().Trim();
                mEntity.TerminalNum = dt.Rows[i]["终端号"].ToString().Trim();
                mEntity.Status = 0;
                var BirthDay = dt.Rows[i]["生产日期"].ToDateTime();
                if (BirthDay == DateTime.MinValue)
                    mEntity.BirthDay = null;
                else
                    mEntity.BirthDay = BirthDay;
                mEntity.Batch = dt.Rows[i]["生产批次"].ToString().Trim();
                OilSalesSerialNumList.Add(mEntity);
            }
            try
            {
                if (Web.Request.QueryString("PageMode") == "Add")
                {
                    Web.Session.Write<List<OilSalesSerialNum>>(Web.Request.QueryString("EntityId")+ "_OilSales", OilSalesSerialNumList);
                    Alert.ShowInTop("序列号已缓存，将在保存单据时同步保存。", "操作结果", MessageBoxIcon.Information, ActiveWindow.GetHidePostBackReference());
                }
                else
                {
                    OilSalesSerialNumContract.AddEntity(OilSalesSerialNumList);
                    Alert.ShowInTop("导入完成", "操作结果", MessageBoxIcon.Information, ActiveWindow.GetHidePostBackReference());
                }
            }
            catch (Exception ee)
            {
                Alert.ShowInTop("导入失败！失败原因：" + ee.ToString(), "操作结果");
            }
        }
    }
}